package com.edu.video.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.entity.HfdVideoInfo;
import com.edu.video.mapper.HfdVideoInfoMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.video.service.IHfdVideoInfoService;
import com.edu.vo.Result;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * <p>
 * 视频表 服务实现类
 * </p>
 *
 * @author jr
 * @since 2021-04-16
 */
@Service
public class HfdVideoInfoServiceImpl extends ServiceImpl<HfdVideoInfoMapper, HfdVideoInfo> implements IHfdVideoInfoService {

    @Autowired
    private HfdVideoInfoMapper hfdVideoInfoMapper;

    /**
     * 添加视频
     *
     * @param hfdVideoInfo
     * @return
     */
    @Override
    public Result addVideo(HfdVideoInfo hfdVideoInfo) {
        int insert = hfdVideoInfoMapper.insert(hfdVideoInfo);
        if (insert > 0) {
            return new Result(true, 80061, "添加视频成功");
        } else {
            return new Result(false, 80060, "添加视频失败");
        }
    }

    /**
     * 查询所有视频信息
     *
     * @return
     */
    @Override
    public Result queryVideo() {
        List<HfdVideoInfo> hfdVideoInfoList = hfdVideoInfoMapper.selectList(null);
        return new Result(true, 80061, "查询成功", hfdVideoInfoList);
    }

    /**
     * 根据video_id删除视频
     *
     * @param video_id
     * @return
     */
    @Override
    public Result deleteVideoById(String video_id) {
        int delete = hfdVideoInfoMapper.deleteById(video_id);
        if (delete > 0) {
            return new Result(true, 80061, "删除成功");
        } else {
            return new Result(false, 80060, "删除失败");
        }
    }

    /**
     * 根据video_id修改视频
     *
     * @param hfdVideoInfo
     * @return
     */
    @Override
    public Result updateVideoById(HfdVideoInfo hfdVideoInfo) {
        int update = hfdVideoInfoMapper.updateById(hfdVideoInfo);
        if (update > 0) {
            return new Result(true, 80061, "修改成功");
        } else {
            return new Result(false, 80060, "修改失败");
        }
    }

    //账号AK信息（必选）
    private static final String accessKeyId = "LTAI5tFXrMHrr2SwvDTcmVFB";
    //账号AK信息（必选）
    private static final String accessKeySecret = "0XpsRdTCKHIxDMRqKsekXDS4j6xibN";

    @Override
    public Result uploadVideo(HfdVideoInfo hfdVideoInfo) {
        //1.音视频上传-本地文件上传
        //视频标题(必选)
        String title = hfdVideoInfo.getTitle();
        //本地文件上传和文件流上传时，文件名称为上传文件绝对路径，如:/User/sample/文件名称.mp4 (必选)
        //文件名必须包含扩展名
        String src = hfdVideoInfo.getSrc();
        System.out.println(src);
        //本地文件上传
        UploadVideoResponse response = testUploadVideo(accessKeyId, accessKeySecret, title, src);
        String videoId = response.getVideoId();
        hfdVideoInfo.setVideoId(videoId);
        if (response.isSuccess()) {
            hfdVideoInfoMapper.insert(hfdVideoInfo);
            return new Result(true, 1, "上传成功");
        } else {
            return new Result(false, 0, "上传失败");
        }
    }

    @Override
    public Result getVideoBySkuId(Integer skuId) {
        QueryWrapper<HfdVideoInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sku_id", skuId);
        HfdVideoInfo videoInfo = this.baseMapper.selectOne(queryWrapper);
        if (videoInfo != null) {
            String playAuth = getPlayAuth(accessKeyId, accessKeySecret, videoInfo.getVideoId());
            videoInfo.setPlayAuth(playAuth);
            return new Result(true, 1, "视频播放成功", videoInfo);
        } else {
            return new Result(false, 0, "该课程没有视频");
        }
    }

    /**
     * 本地文件上传接口
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @param title
     * @param fileName
     */
    private UploadVideoResponse testUploadVideo(String accessKeyId, String accessKeySecret, String title, String fileName) {
        UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
        /*可指定分片上传时每个分片的大小，默认为1M字节*/
        request.setPartSize(1 * 1024 * 1024L);
        /*可指定分片上传时的并发线程数，默认为1（注：该配置会占用服务器CPU资源，需根据服务器情况指定）*/
        request.setTaskNum(1);
        /*是否开启断点续传，默认断点续传功能关闭。当网络不稳定或者程序崩溃时，再次发起相同上传请求，可以继续未完成的上传任务，适用于超时3000秒仍不能上传完成的大文件。
        注意: 断点续传开启后，会在上传过程中将上传位置写入本地磁盘文件，影响文件上传速度，请您根据实际情况选择是否开启*/
        request.setEnableCheckpoint(false);
        /*OSS慢请求日志打印超时时间，是指每个分片上传时间超过该阈值时会打印debug日志，如果想屏蔽此日志，请调整该阈值。单位: 毫秒，默认为300000毫秒*/
        //request.setSlowRequestsThreshold(300000L);
        /*可指定每个分片慢请求时打印日志的时间阈值，默认为300s*/
        //request.setSlowRequestsThreshold(300000L);
        /*是否使用默认水印（可选），指定模板组ID时，根据模板组配置确定是否使用默认水印*/
        //request.setIsShowWaterMark(true);
        /*自定义消息回调设置（可选），参数说明参考文档 https://help.aliyun.com/document_detail/86952.html#UserData*/
        // request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackURL\":\"http://test.test.com\"}}");

        /*视频分类ID（可选）*/
        //request.setCateId(0);
        /*视频标签,多个用逗号分隔（可选）*/
        //request.setTags（"标签1,标签2"）;
        /*视频描述（可选）*/
        //request.setDescription("视频描述");
        /*封面图片（可选）*/
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /*模板组ID（可选）*/
        //request.setTemplateGroupId("8c4792cbc8694*****d5330e56a33d");
        /*点播服务接入点*/
        //request.setApiRegionId("cn-shanghai");
        /*ECS部署区域，如果与点播存储（OSS）区域相同，则自动使用内网上传文件至存储*/
        // request.setEcsRegionId("cn-shanghai");
        /*存储区域（可选）*/
        //request.setStorageLocation("in-2017032*****18266-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        /*开启默认上传进度回调*/
        // request.setPrintProgress(true);
        /*设置自定义上传进度回调（必须继承 ProgressListener）*/
        // request.setProgressListener(new PutObjectProgressListener());
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
        } else {
            /* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
        return response;
    }

    private String getPlayAuth(String accessKeyId, String accessKeySecret, String videoId) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setRegionId("cn-hangzhou");
        request.setVideoId(videoId);
        try {
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            return response.getPlayAuth();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return null;
    }

}
